package ute.mvc.controller.portal.admin;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import ute.mvc.model.User;
import ute.mvc.model.User.GroupAdd;
import ute.mvc.model.User.GroupEdit;
import ute.mvc.service.UserService;
import ute.mvc.util.Item;
import ute.mvc.util.JsonObject;

@Controller
@RequestMapping(value = { "/portal/user" })
public class UserController {

	@Autowired
	UserService userService;

	/**
	 * Get all users from database
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = { "/list", "/" })
	public String getAllUser(Model model, HttpServletRequest request) {

		return "user_list";
	}

	/**
	 * Add new user
	 * 
	 * @param model
	 * @return
	 */

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String getAddUser(Model model) {

		List<Item> userType = new ArrayList<Item>();
		Item item = new Item(3, "Student");
		userType.add(item);
		item = new Item(2, "Lecturer");
		userType.add(item);
		item = new Item(1, "Moderator");
		userType.add(item);

		model.addAttribute("userType", userType);
		model.addAttribute("user", new User());
		return "user_add";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String addUser(@Validated(GroupAdd.class) @ModelAttribute User user,
			BindingResult result, Model model) {

		List<Item> userType = new ArrayList<Item>();
		Item item = new Item(3, "Student");
		userType.add(item);
		item = new Item(2, "Lecturer");
		userType.add(item);
		item = new Item(1, "Moderator");
		userType.add(item);

		model.addAttribute("userType", userType);

		if (result.hasErrors()) {
			return "user_add";
		}

		User existUser = userService.getUserByEmail(user.getEmail());
		if (existUser != null) {
			result.rejectValue("email", "userNameExist");
			return "user_add";
		}

		userService.addUser(user);
		return "redirect:list";
	}

	/**
	 * Edit user information
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String getEditUser(@PathVariable int id, Model model) {

		User user = userService.getUserById(id);
		model.addAttribute("user", user);
		return "user_edit";
	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
	public String editUser(@PathVariable int id,
			@Validated(GroupEdit.class) @ModelAttribute User user,
			BindingResult result, Model model) {

		if (result.hasErrors()) {
			return "user_edit";
		}
		
		User existUser = userService.getUserByEmail(user.getEmail());
		if (existUser != null && user.getUserId() != existUser.getUserId()) {
			result.rejectValue("email", "userNameExist");
			return "user_edit";
		}
		userService.updateUser(user);
		return "redirect:../edit/" + user.getUserId();
	}

	/**
	 * 
	 * @return JSON method
	 */

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@ResponseBody
	@RequestMapping("/listJSON")
	public JsonObject getAllUserJSON() {

		System.out.println("JSON");
		List<User> list = new ArrayList<User>();

		list = userService.getAllUser();

		// System.out.println(list.size());
		JsonObject userJson = new JsonObject();
		userJson.setAaData(list);
		userJson.setsEcho(1);
		userJson.setiTotalDisplayRecords(list.size());
		userJson.setiTotalRecords(list.size());
		return userJson;
	}

	@ResponseBody
	@RequestMapping("/delete")
	public String deleteSelectedUser(@RequestBody String users, HttpServletRequest request) {
		String[] ids = users.split(";");
		
		//check if admin want to delete his user!
		User user = (User) request.getSession().getAttribute("user");
		for(String id : ids) {
			if(Integer.parseInt(id) == user.getUserId())
				return "fail";
		}
		
		// try to delete users
		if(userService.deleteUsers(ids)) {
			return "success";
		} else {
			return "fail";
		}
	}
}
